﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using PLM.ConfigurationCenter.Backup.Handle;
using PLM.ConfigurationCenter.Service;
using Quartz;

namespace PLM.ConfigurationCenter.Backup.Jobs {
    /// <summary>
    /// 
    /// </summary>
    [DisallowConcurrentExecution]
    public class DataBaseBackupJob : IJob {
        private readonly TaskService taskService = new TaskService();
        private readonly BackupService backupService = new BackupService();
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Execute(IJobExecutionContext context) {
            Action<string>? Job = null;
            await Task.Run(() => {
                try {
                    Job = (Action<string>)context.JobDetail.JobDataMap.Get("action");
                    Job?.Invoke("Job开始执行！");
                    var id = context.JobDetail.Key.Name;
                    if (!string.IsNullOrWhiteSpace(id)) {
                        id = id.Replace("Job", "").Trim();
                    }
                    var model = taskService.GetById(id);
                    bool res = backupService.DataBaseBackup(model, out string error);
                    if (res) {
                        Job?.Invoke("Job执行成功！");
                    } else {
                        Job?.Invoke($"Job执行失败！,{error}");
                    }
                } catch (Exception ex) {
                    Job?.Invoke($"Job执行失败！,{ex.Message}");
                } finally {
                    Job?.Invoke($"Job执行结束！");
                }
            });
        }
    }
}
